package vip.xiaonuo.modular.vxpay.service;

import com.alibaba.druid.util.StringUtils;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.springframework.util.ResourceUtils;
import vip.xiaonuo.core.util.MD5Util;
import vip.xiaonuo.core.util.MyX509TrustManager;
import vip.xiaonuo.core.util.PastTimeFormatUtil;
import vip.xiaonuo.core.util.StrUtils;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.math.BigDecimal;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLDecoder;
import java.security.*;
import java.util.*;

public class PaymentService {
    public static final String APPID = "wx4cbb499054bd3275";      //服务号APPID
    public static final String AppSecret = "1cb120229b31f9c221f706c98ec1bc3a";  //服务号AppSecret
    public static final String MCH_ID = "1613969477";      // 微信支付分配的商户号
    public static final String API_KEY = "jH17BDg0kv24IKctSzasX30HeZbE0sgo";    //API密钥
    // 微信商户证书路径
    public static final String certPath = "apiclient_cert.p12";
    // 商户名称, 如'XXX服务号'
    private static String mchName = "熊小记";
    //证书密码
    private static String sslPassword ="1613969477";
    // 请求器的配置
    private static RequestConfig requestConfig;
    // 连接超时时间，默认10秒
    private static int socketTimeout = 10000;
    // 传输超时时间，默认30秒
    private static int connectTimeout = 30000;

    /**
     *微信提现
     * @param openid 用户的openid 必填 用户提现需要判断是小程序还是APP,小程序传小程序openid，app传微信openId(app登录使用)
     * @param amount 付款金额 单位为元 必填
     * @return result 返回结果列子（是一个xml字符串）： <xml>
     *
     * <return_code><![CDATA[SUCCESS]]></return_code>
     *
     * <return_msg><![CDATA[]]></return_msg>
     *
     * <mch_appid><![CDATA[wxec38b8ff840bd989]]></mch_appid>
     *
     * <mchid><![CDATA[10013274]]></mchid>
     *
     * <device_info><![CDATA[]]></device_info>
     *
     * <nonce_str><![CDATA[lxuDzMnRjpcXzxLx0q]]></nonce_str>
     *
     * <result_code><![CDATA[SUCCESS]]></result_code>
     *
     * <partner_trade_no><![CDATA[10013574201505191526582441]]></partner_trade_no>
     *
     * <payment_no><![CDATA[1000018301201505190181489473]]></payment_no>
     *
     * <payment_time><![CDATA[2015-05-19 15：26：59]]></payment_time>
     *
     * </xml>
     * 判断 失败：result.contains("CDATA[FAIL]") 返回true 失败 false成功
     *   SAXBuilder saxBuilder = new SAXBuilder();
     *   Document doc = saxBuilder.build(new StringReader(result));
     * 获取错误原因：return doc.getRootElement().getChild("err_code_des").getValue();
     * 成功 获取交易单号：return doc.getRootElement().getChild("payment_no").getValue();
     */
    public static String doTransfers( String openid, BigDecimal amount){
        String result ="success";
        try
        {
            String nonceStr = StrUtils.getOrderIdByTime();
            // 1.计算参数签名
            SortedMap<String, String> parameters = new TreeMap<String, String>();
            String a = amount.multiply(new BigDecimal("100")).intValue() + "";
            System.out.println("提交金额"+a);
            parameters.put("amount", a);
            parameters.put("check_name", "NO_CHECK");
            String encode = "UTF-8";
            if (mchName.equals(new String(mchName.getBytes("UTF-8"), encode))) {
                String s = encode;
                System.out.println(s);
            }
            parameters.put("desc", mchName);
            parameters.put("mchid", MCH_ID);
            parameters.put("mch_appid", APPID);
            parameters.put("nonce_str", nonceStr);
            parameters.put("openid", openid);
            parameters.put("partner_trade_no", StrUtils.getOrderIdByTime());
            parameters.put("sign", createSign(parameters, API_KEY));
            String data = SortedMaptoXml(parameters);
            data = new String(data.getBytes(), "utf-8");
            // 3.加载证书请求接口
            System.out.println(data);
            result = weChatWithdrawal(data);
            System.out.println(result);
            /*if(result.contains("CDATA[FAIL]")){
                SAXBuilder saxBuilder = new SAXBuilder();
                Document doc = saxBuilder.build(new StringReader(result));
                return doc.getRootElement().getChild("err_code_des").getValue();
            }*/
        }
        catch (Exception e) {
            e.printStackTrace();
            return "微信提现失败";
        }
        return result;
    }


    /**
     * 证书使用
     * 微信提现
     */
    @SuppressWarnings("deprecation")
    public static String weChatWithdrawal(String data) throws Exception {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");

        StringBuffer pkcsPath = new StringBuffer();
        pkcsPath.append("classpath:").append(certPath);
        System.out.println("certPath"+certPath);
        InputStream instream = null;
        try {
            instream = ResourceUtils.getURL(pkcsPath.toString()).openStream();
        } catch (IOException var10) {
        }

        if (instream == null) {
            return null;
        }

        String result = "";
        try {
            keyStore.load(instream, sslPassword.toCharArray());
        } finally {
            instream.close();
        }

        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, sslPassword.toCharArray())
                .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[]{"TLSv1"},
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
        try {
            HttpPost httppost = new HttpPost("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers");
            StringEntity entitys = new StringEntity(data,"UTF-8");
            httppost.setEntity((HttpEntity) entitys);
            // 根据默认超时限制初始化requestConfig
            requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
            // 设置请求器的配置
            httppost.setConfig(requestConfig);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity,"UTF-8");
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
        return result;
    }


    /**
     * 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
     */
    public static String createSign(SortedMap<String, String> packageParams, String AppKey) {
        StringBuffer sb = new StringBuffer();
        Set es = packageParams.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + AppKey);
        String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
        return sign;
    }

    /**
     * @param params
     * @Author:
     * @Description:请求值转换为xml格式 SortedMap转xml
     */
    private static String SortedMaptoXml(SortedMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder sb = new StringBuilder();
        Set es = params.entrySet();
        Iterator it = es.iterator();
        sb.append("<xml>\n");
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            sb.append("<" + k + ">");
            sb.append(v);
            sb.append("</" + k + ">\n");
        }
        sb.append("</xml>");
        return sb.toString();
    }

    /**
     * 发起https请求并获取结果
     *
     * @param requestUrl    请求地址
     * @param requestMethod 请求方式（GET、POST）
     * @param outputStr     提交的数据
     * @return JSONObject(通过JSONObject.get ( key)的方式获取json对象的属性值)
     */
    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            System.err.println("Weixin server connection timed out.");
        } catch (Exception e) {
            System.err.println("https request error");
        }
        return jsonObject;
    }

    public static String getPrepayId(HttpServletRequest request, String name, String orderno, String total_fee, String openid) throws Exception {
        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
        BigDecimal decimal = new BigDecimal(total_fee);
        decimal.multiply(new BigDecimal(100));
        parameters.put("appid", APPID);
        parameters.put("mch_id", MCH_ID);
        parameters.put("nonce_str", CreateNoncestr());
        parameters.put("body", name);
        parameters.put("out_trade_no", orderno);// 订单号
        parameters.put("total_fee", decimal);// 支付金额单位：分
        parameters.put("spbill_create_ip", getIp2(request));
        parameters.put("notify_url", "支付成功回调地址");
        parameters.put("trade_type", "JSAPI");
        parameters.put("openid", openid);//openid :需填写
        parameters.put("time_expire", PastTimeFormatUtil.getWxPayTime());// 交易结束时间,需要动态传入,格式为yyyyMMddHHmmss
        String sign = createSign("UTF-8", parameters);
        parameters.put("sign", sign);
        String requestXML = getRequestXml(parameters);
        //调用统一下单接口
        String result = httpsRequest("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST", requestXML);
        System.out.println(result);
        return result;
    }


    public static String CreateNoncestr() {
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        String res = "";
        for (int i = 0; i < 16; i++) {
            Random rd = new Random();
            res += chars.charAt(rd.nextInt(chars.length() - 1));
        }
        return res;
    }

    public static String getIp2(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }

    @SuppressWarnings("rawtypes")
    public static String createSign(String characterEncoding, SortedMap<Object, Object> parameters) {
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + API_KEY);
        String sign = MD5Encode(sb.toString(), characterEncoding).toUpperCase();
        return sign;
    }

    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname))
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
            else
                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
        } catch (Exception exception) {
        }
        return resultString;
    }

    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++)
            resultSb.append(byteToHexString(b[i]));
        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n += 256;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    @SuppressWarnings("rawtypes")
    public static String getRequestXml(SortedMap<Object, Object> parameters) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
                sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
            } else {
                sb.append("<" + k + ">" + v + "</" + k + ">");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }


    /**
     * 发送https请求
     *
     * @param requestUrl    请求地址
     * @param requestMethod 请求方式（GET、POST）
     * @param outputStr     提交的数据
     * @return 返回微信服务器响应的信息
     */
    public static String httpsRequest(String requestUrl, String requestMethod,
                                      String outputStr) {
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("content-type",
                    "application/x-www-form-urlencoded");
            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            return buffer.toString();
        } catch (ConnectException ce) {
            System.out.println("连接超时");
        } catch (Exception e) {
            System.out.println("请求异常");
        }
        return null;
    }

    public static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    public static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

    /**
     * 解析xml
     */
    public static Map doXMLParse(String strxml) throws Exception {
        strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");

        if (null == strxml || "".equals(strxml)) {
            return null;
        }

        Map m = new HashMap();

        InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List list = root.getChildren();
        Iterator it = list.iterator();
        while (it.hasNext()) {
            Element e = (Element) it.next();
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if (children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = getChildrenText(children);
            }

            m.put(k, v);
        }
        // 关闭流
        in.close();
        return m;
    }

    /**
     * 获取子结点的xml
     */
    public static String getChildrenText(List children) {
        StringBuffer sb = new StringBuffer();
        if (!children.isEmpty()) {
            Iterator it = children.iterator();
            while (it.hasNext()) {
                Element e = (Element) it.next();
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<" + name + ">");
                if (!list.isEmpty()) {
                    sb.append(getChildrenText(list));
                }
                sb.append(value);
                sb.append("</" + name + ">");
            }
        }
        return sb.toString();
    }


}